package security.user.service.impl;


import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.MongoOperations;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.alibaba.fastjson.JSON;

import lombok.extern.slf4j.Slf4j;
import security.user.model.Role;
import security.user.model.SecurityUser;
import security.user.model.User;

@Service
@Slf4j
public class UserDetailsServiceMongoDBImpl implements UserDetailsService {

	@Autowired
	MongoOperations operations;
	@Override
	public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
		// 提取client
		ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
		String client = attributes.getRequest().getParameter("client");
		if(client==null||client.isBlank()) {
			log.info("未知的客户端标识");
			throw new UsernameNotFoundException("no such client! ");
		}
		
		System.out.println(username+" 开始登录...");
		Query query=new Query();
		query.fields().include("id").include("username").include("password").include("email").include("roleIds").include("phone").include("qq").include("aliPay").include("weChat");
		query.addCriteria(Criteria.where("username").is(username));
		User user=operations.findOne(query, User.class);
		System.out.println(JSON.toJSONString(user, true));
		if(user==null) {
			throw new UsernameNotFoundException("no such soccer! "+username);
		}
		SecurityUser securityUser=new SecurityUser();
		securityUser.setId(user.getId());

		//重新登录不需要密码
		String login_type=attributes.getRequest().getParameter("login_type");
		if(login_type!=null&&login_type.equals("re_login")){
			System.out.println("this is re_login");
			securityUser.setPassword(new BCryptPasswordEncoder().encode("withoutPassword"));
		}else{
			securityUser.setPassword(user.getPassword());
		}

		securityUser.setUsername(user.getUsername());
		securityUser.setEmail(user.getEmail());
		securityUser.setMobile(user.getPhone());
		securityUser.setQq(user.getQq());
		securityUser.setAliPay(user.getAliPay());
		securityUser.setWeChat(user.getWeChat());
		loadRolesByUser(user,client).forEach(r->{
			if(!r.isExpired()&&client.equals(r.getClient())){
				securityUser.getRoles().add(r.getName());
			}
		});

		return securityUser;
	}
	
	private List<Role> loadRolesByUser(User user,String client){
		List<Role> roles=operations.find(Query.query(Criteria.where("id").in(user.getRoleIds())), Role.class);
		if(roles.size()==0) {
			Role normalRole = Role.NormalRole(LocalDate.now().plusYears(50));
			normalRole.setClient(client);
			roles.add(normalRole);
		}
		roles.forEach(System.out::println);
		return roles;		
	}

}
